package top.saplf.sileny.util

import android.os.Environment
import com.jakewharton.disklrucache.DiskLruCache
import top.saplf.sileny.BuildConfig
import top.saplf.sileny.SilenyApplication
import top.saplf.sileny.ext.ensureExist
import java.io.File

/**
 * @author Saplf on 17/4/9
 */
private val app: SilenyApplication by lazy { SilenyApplication.app }
private val imgDir: String by lazy { "image" }
private val imgCache: File by lazy { getDiskCacheDir(imgDir).ensureExist() }

fun getDiskCacheDir(uniqueName: String): File =
        if (Environment.MEDIA_MOUNTED == Environment.getExternalStorageState()
                || !Environment.isExternalStorageRemovable()) {
            File("${app.externalCacheDir.path}${File.separator}$uniqueName")
        } else {
            File("${app.cacheDir.path}${File.separator}$uniqueName")
        }

fun cacheByteArray(key: String, byteArray: ByteArray) {
    val diskLruCache = DiskLruCache.open(imgCache, BuildConfig.VERSION_CODE, 1, 10 shl 20)
    val edit: DiskLruCache.Editor? = diskLruCache.edit(key)
    if (edit != null) with(edit) {
        newOutputStream(0).use { it.write(byteArray) }
        commit()
    }
}

fun getByteArrayCache(key: String): ByteArray? {
    val snapshot: DiskLruCache.Snapshot? = DiskLruCache.open(imgCache, BuildConfig.VERSION_CODE, 1, 10 shl 20)[key]
    return if (snapshot == null) {
        null
    } else {
        snapshot.edit().newInputStream(0).use { it.readBytes() }
    }
}
